import 'package:flutter/material.dart';
import 'package:hand_writing/database/database.dart';
import 'package:hand_writing/uril/color.dart';
import 'package:hand_writing/uril/date.dart';
import 'package:provider/provider.dart';

import '../../componts/write_box/write_box_view.dart';
import 'index_provider.dart';

class IndexPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final provider = context.watch<IndexProvider>();

    return _buildPage(context, provider);
  }

  Widget _buildPage(BuildContext context, IndexProvider provider) {
    final provider = context.read<IndexProvider>();
    final state = provider.state;

    return Scaffold(
      backgroundColor: Color(0xFFF3EFEE),
      body: CustomScrollView(
        slivers: [
          // 可吸顶的标题
          SliverAppBar(
            pinned: true,
            expandedHeight: 120,
            // backgroundColor: Colors.white,
            flexibleSpace: LayoutBuilder(
              builder: (BuildContext context, BoxConstraints constraints) {
                // 当前高度（收缩时约 80，高度收起时约 minExtent）
                double top = constraints.biggest.height;

                // 计算收缩比（0～1）
                double shrinkRatio =
                    (top - kToolbarHeight) / (120 - kToolbarHeight);

                return Container(
                  color: Color(0xFFF3EFEE),
                  padding: EdgeInsets.only(
                    top: MediaQuery.of(context).padding.top,
                  ),
                  child: Stack(
                    alignment: Alignment.bottomCenter,
                    children: [
                      Positioned(
                        left: 0,
                        right: 0,
                        bottom: 12,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                const SizedBox(width: 20), // 左占位空白
                                Text(
                                  '手记',
                                  style: TextStyle(
                                    fontSize: 20 + 10 * shrinkRatio,
                                    // 滚动时字号变化
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                            Padding(
                              padding: const EdgeInsets.only(right: 16),
                              child: PopupMenuButton<String>(
                                icon: Icon(
                                  Icons.filter_list,
                                  color: Colors.black,
                                ),
                                itemBuilder:
                                    (context) => [
                                      PopupMenuItem(
                                        value: 'all',
                                        child: Text('所有手记'),
                                      ),
                                      PopupMenuItem(
                                        value: 'picture',
                                        child: Text('照片'),
                                      ),
                                      PopupMenuItem(
                                        value: 'address',
                                        child: Text('地点'),
                                      ),
                                    ],
                                onSelected: (value) {
                                  // TODO: 筛选逻辑
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),

          SliverList(
            delegate: SliverChildBuilderDelegate(
                  (context, index) {
                return WriteBoxPage(
                    key: ValueKey(context.watch<IndexProvider>().state.notes[index].id), // 加上唯一 Key
                    note: context.watch<IndexProvider>().state.notes[index],
                    appDatabase: context.read<IndexProvider>().database
                );
              },
              childCount: context.watch<IndexProvider>().state.notes.length,
            ),
          ),

        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,

      floatingActionButton: SizedBox(
        height: 80,
        width: 80,
        child: FloatingActionButton(
          shape: CircleBorder(),
          onPressed:()=>context.read<IndexProvider>().showEdit(context,Note(id: 0, content: '', createdAt: DateTime(2000,1,1))),
          backgroundColor: Colors.white,
          child: Icon(
            Icons.add,
            color: ColorUtil.parseColor("#6866d2"),
            size: 50,
          ),
        ),
      ),
    );
  }
}

class NoteEditorSheet extends StatefulWidget {
  @override
  State<NoteEditorSheet> createState() => _NoteEditorSheetState();
}

class _NoteEditorSheetState extends State<NoteEditorSheet> {
  late TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    final str = context.read<IndexProvider>().state.note?.content;
    _controller = TextEditingController(text: str);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return  SizedBox(
        height: MediaQuery.of(context).size.height * 0.9, // 占 75% 高度
        child:Column(
          children: [
            // 顶部按钮
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(onPressed: () {}, child: Text("")),
                  Text(
                    DateUtil.formatDateTimeToChineseNoYear(DateTime.now()),
                    style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
                  ),
                  TextButton(
                    onPressed: () {

                      context.read<IndexProvider>().saveNote(context);
                      // print(_controller.text); // 或 context.read<IndexProvider>().state.str
                      // print(context.read<IndexProvider>().state.str); // 或 context.read<IndexProvider>().state.str
                    },
                    child: Text(
                      "完成",
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: ColorUtil.parseColor("#6866d2"),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: TextField(
                controller: _controller,
                autofocus: true,
                maxLines: null,
                expands: true,
                keyboardType: TextInputType.multiline,
                style: TextStyle(fontSize: 16),
                decoration: InputDecoration(
                  hintText: "开始记录...",
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                ),
                onChanged: (val) {
                  context.read<IndexProvider>().changeStr(val);
                },
              ),
            ),
          ],
        )
    );
  }
}


class _AutoGrowingTextField extends StatefulWidget {
  @override
  State<_AutoGrowingTextField> createState() => _AutoGrowingTextFieldState();
}

class _AutoGrowingTextFieldState extends State<_AutoGrowingTextField> {
  final TextEditingController _controller = TextEditingController();
  int _maxLines = 5;

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller,
      maxLines: null,
      // 允许无限行
      minLines: 1,
      keyboardType: TextInputType.multiline,
      decoration: InputDecoration(
        hintText: "在这里输入内容...",
        border: OutlineInputBorder(),
        contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 12),
      ),
      onChanged: (text) {
        setState(() {
          _maxLines = '\n'.allMatches(text).length + 1;
        });
      },
    );
  }
}
